﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Threading;
using Cartography.Desktop;

namespace GPS
{
    public class GPSService
    {
        private static GPSService instance = null;
        private static GPSDevice dev;
        private static bool finish = false;

        private static HashSet<GPSInterface> listeners = new HashSet<GPSInterface>();
        private static Object lockthis = new Object();

        private static int updateTime = 500;

        public static int UpdateTime
        {
            get
            {
                return updateTime;
            }
            set
            {
                updateTime = value;
            }
        }

        private GPSService(string port, int bps)
        {
            dev = new GPSDevice(port, bps);
        }
        public static GPSService getInstance()
        {
            return instance;
        }
        public static void configure(string port, int bps)
        {
            instance = new GPSService(port, bps);
        }

        public static bool add(GPSInterface listener)
        {
            // Registrarse como listener
            bool ret;
            lock (lockthis)
                ret = listeners.Add(listener);

            return ret;
        }

        public static bool remove(GPSInterface listener)
        {
            // Anular suscripción como listener
            bool ret;
            lock (lockthis)
                ret = listeners.Add(listener);

            return ret;
        }

        public static void service()
        {
            // Ejecutable del Thread que notificará a los listeners
            try
            {
                while (true)
                {
                    // Obtener la posición
                    //GPSData posicion = dev.getLatLong();
                    // Notificar a los listeners que hay información disponible
                    lock (lockthis)
                    {
                        foreach (GPSInterface listener in listeners)
                        {
                            //listener.notify(posicion.coords);
                            listener.notify(new LatLon("-33.46727","-70.58175"));
                        }
                    }

                    // Al finalizar, dormirse un rato
                    Thread.Sleep(updateTime); // La posición se actualizará cada 1 seg
                }
            }
            catch (ThreadAbortException) { }
        }

        public static bool Finish
        {
            set
            {
                finish = value;
            }
        }

        public GPSDevice Device
        {
            get
            {
                return dev;
            }
        }
    }
}
